import React, {Component, Suspense} from 'react';
import Loading from '../components/Loading';
import { Redirect, Route, Switch, withRouter } from "react-router-dom";
import Login from '../pages/Login';
import routes from './config';
import TabBar from '../components/TabBar';

import {connect} from 'react-redux';

const tabBars = routes.map(item=> {
	if (item.showTabBar) {
		return item.path
	}
})

class Router extends Component {
	render() {
		const {user, location} = this.props;
		const {pathname} = location;
		const isLogin = user.token !== undefined;
		return isLogin ? (
			<>
				<Suspense fallback={<Loading/>}>
					<Switch>
						{
							routes.map( (routeObj, index) => {
								return <Route path={routeObj.path} component={routeObj.component} key={index}/>
							})
						}
						{/* 默认路由 */}
						<Redirect to="/404"/>
					</Switch>
				</Suspense>
				{
					tabBars.indexOf(pathname)!==-1 ? <TabBar/> : <></>
				}

			</>
		): (
			<>
				<Route path="/login" component={Login}/>
				{/* 默认路由 */}
				<Redirect to="/login"/>
			</>
		);
	}
}

export default withRouter(connect(
	state => ({
		user: state.user,
		count: state.count
	})
)(Router))